<template>
  <view class="expansion-detail-container">
    <u-navbar
      title="拓展详情"
      :border-bottom="false"
      back-icon-color="#007aff"
      back-text="返回"
      :back-text-style="{color: '#007aff'}"
      :custom-style="{background: '#ffffff', boxShadow: '0 2px 10px rgba(0, 0, 0, 0.05)'}"
      :safe-area-inset-top="true"
      :auto-back="true"
      fixed
    ></u-navbar>

    <!-- 导航栏占位，解决fixed定位导致的内容被遮挡问题 -->
    <view class="navbar-placeholder"></view>

    <scroll-view
      scroll-y
      class="detail-scroll-view"
      :refresher-enabled="true"
      :refresher-triggered="isRefreshing"
      refresher-background="#f7f8fa"
      @refresherrefresh="onRefresh"
      @scroll="onScroll"
    >
      <view class="content">
        <view class="header-card">
          <view
            class="status-badge"
            :class="'status-' + expansionInfo.status"
          >{{ getStatusText(expansionInfo.status) }}</view>

          <view class="group-info">
            <view class="group-name">{{ expansionInfo.groupName }}</view>
            <view class="info-meta">
              <text>{{ expansionInfo.categoryName }} / {{ expansionInfo.productName }}</text>
            </view>
          </view>

          <view class="amount-info">
            <text class="amount-label">预计金额</text>
            <text class="amount-value">{{ formatMoney(expansionInfo.amount) }}</text>
            <text class="amount-unit">元/年</text>
          </view>
        </view>

        <view class="info-section">
          <view class="section-title">
            <u-icon name="info-circle" color="#2b85e4" size="32"></u-icon>
            <text>信息化产品拓展信息</text>
            <view class="edit-expansion" @click="goToEditPage">
              <u-icon name="edit-pen" color="#2b85e4" size="28"></u-icon>
              <text>编辑</text>
            </view>
          </view>

          <view class="info-items">
            <view class="info-card">
              <view class="info-item">
                <text class="item-label">所属集团</text>
                <text class="item-value highlight">{{ expansionInfo.groupName }}</text>
              </view>

              <view class="info-item">
                <text class="item-label">产品类别</text>
                <text
                  class="item-value"
                >{{ expansionInfo.categoryName }}-{{ expansionInfo.productName }}</text>
              </view>

              <view class="info-item">
                <text class="item-label">产品数量</text>
                <text class="item-value">{{ expansionInfo.quantity || '暂无' }}</text>
              </view>

              <view class="info-item">
                <text class="item-label">预计金额</text>
                <text class="item-value price">{{ formatMoney(expansionInfo.amount) }}元/年</text>
              </view>
            </view>

            <view class="info-card">
              <view class="info-item">
                <text class="item-label">预计落地时间</text>
                <text class="item-value">{{ expansionInfo.expectedTime }}</text>
              </view>

              <view class="info-item">
                <text class="item-label">项目/服务包</text>
                <text class="item-value">{{ expansionInfo.isProject ? '是' : '否' }}</text>
              </view>

              <view class="info-item">
                <text class="item-label">产品主管</text>
                <text class="item-value">{{ expansionInfo.manager || '暂无' }}</text>
              </view>

              <view class="info-item">
                <text class="item-label">创建时间</text>
                <text class="item-value">{{ expansionInfo.createTime }}</text>
              </view>
            </view>

            <view class="info-card policy-card">
              <view class="card-subtitle">
                <u-icon name="grid" color="#19be6b" size="28"></u-icon>
                <text>投放政策及资费</text>
              </view>
              <text class="policy-text">{{ expansionInfo.policy || '暂无' }}</text>
            </view>
          </view>
        </view>

        <view class="follow-section">
          <view class="section-title">
            <u-icon name="chat" color="#2b85e4" size="32"></u-icon>
            <text>跟进记录 ({{ followList.length }})</text>
            <view class="add-follow" @click="showAddFollowPopup">
              <u-icon name="plus-circle" color="#2b85e4" size="28"></u-icon>
              <text>跟进</text>
            </view>
          </view>

          <view class="follow-timeline">
            <u-empty v-if="followList.length === 0" mode="list" text="暂无跟进记录" margin-top="40"></u-empty>

            <!-- 将折叠面板改为时间轴方式 -->
            <view class="progress-timeline" v-else>
              <view class="timeline-item" v-for="(item, itemIndex) in followList" :key="itemIndex">
                <view class="timeline-left">
                  <view class="timeline-dot" :class="'status-' + item.status"></view>
                  <view class="timeline-line" v-if="itemIndex !== followList.length - 1"></view>
                </view>
                <view class="timeline-right">
                  <view class="timeline-header">
                    <text class="timeline-date">{{ formatDate(item.followTime) }}</text>
                    <view class="timeline-actions" v-if="expansionInfo.status === '跟进中'">
                      <view class="action-btn edit-btn" @click.stop="editFollow(item)">
                        <u-icon name="edit-pen" size="12" color="#2b85e4"></u-icon>
                      </view>
                      <view class="action-btn delete-btn" @click.stop="deleteFollow(item.id)">
                        <u-icon name="trash" size="12" color="#fa3534"></u-icon>
                      </view>
                    </view>
                    <view class="timeline-user" v-else>
                      <u-icon name="account" size="14" color="#7f8c8d" margin-right="4"></u-icon>
                      {{ item.follower }}
                    </view>
                  </view>
                  <view class="timeline-content">
                    <view class="content-header">
                      <view class="timeline-user" v-if="expansionInfo.status === '跟进中'">
                        <u-icon name="account" size="14" color="#7f8c8d" margin-right="4"></u-icon>
                        {{ item.follower }}
                      </view>
                    </view>
                    <view class="content-text">{{ item.content }}</view>

                    <view class="content-details">
                      <view class="detail-item" v-if="item.status === '已落地'">
                        <text class="detail-label">实际金额:</text>
                        <text class="detail-value">{{ formatMoney(item.actualAmount) }}元/年</text>
                      </view>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <view
      class="bottom-actions"
      :style="{ transform: showBottomActions ? 'translateY(0)' : 'translateY(100%)' }"
    >
      <u-button v-if="expansionInfo.status == '跟进中'" type="error" text="标记废弃" @click="markAsFailed"></u-button>

      <u-button
        v-if="expansionInfo.status === '跟进中'"
        type="success"
        text="标记签约"
        @click="markAsCompleted"
      ></u-button>
    </view>

    <!-- 添加跟进弹窗 -->
    <view class="custom-popup-mask" v-if="showPopup" @click.stop="onMaskClick">
      <view class="custom-popup-content" @click.stop>
        <view class="custom-popup-close" @click="closePopup">×</view>
        <view class="popup-content">
          <view class="popup-title">{{ popupTitle }}</view>

          <view class="form-content">
            <view class="popup-product-info">
              <view class="popup-product-name">{{ expansionInfo.productName }}</view>
              <view
                class="popup-product-status"
                :class="'status-' + expansionInfo.status"
              >{{ getStatusText(expansionInfo.status) }}</view>
            </view>

            <view class="form-group">
              <view class="form-label required">跟进日期</view>
              <view class="form-control date-picker">
                <picker
                  mode="date"
                  :value="form.followTime ? form.followTime.split(' ')[0] : ''"
                  :end="getCurrentDate(true)"
                  @change="dateChange"
                >
                  <view class="picker-value">
                    <text>{{ form.followTime || '请选择日期' }}</text>
                    <u-icon name="arrow-right" size="16" color="#c0c4cc"></u-icon>
                  </view>
                </picker>
              </view>
            </view>

            <view class="form-group">
              <view class="form-label required">目前跟进情况</view>
              <view class="form-control">
                <u-textarea
                  v-model="form.content"
                  placeholder="支持按日期记录更新内容，例：拜访客户单位***，沟通了**产品的报价及设计方案，**意向8月份建设，对我公司该项产品的意见为......"
                  height="100"
                  count
                  maxlength="300"
                ></u-textarea>
              </view>
            </view>
          </view>

          <view class="popup-footer">
            <u-button type="default" shape="circle" @click="closePopup" :plain="true">取消</u-button>
            <u-button type="primary" shape="circle" @click="saveFollow" :loading="isSaving">保存</u-button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      expansionId: "",
      groupCode: "",
      expansionInfo: {
        id: "",
        groupName: "",
        categoryName: "",
        productName: "",
        quantity: 0,
        amount: 0,
        expectedTime: "",
        createTime: "",
        status: "progress", // progress, completed, failed
        isProject: false,
        policy: "",
        manager: ""
      },
      followList: [],

      // 弹窗相关数据
      showPopup: false,
      isSaving: false,
      popupTitle: "新增跟进记录", // 弹窗标题
      isEdit: false, // 是否是编辑操作

      // 滚动交互相关
      isRefreshing: false,
      scrollTop: 0,
      showBottomActions: true,
      lastScrollTop: 0,

      // 表单数据
      form: {
        status: "",
        statusText: "",
        followTime: "",
        content: "",
        actualAmount: "",
        signDate: ""
      },

      // 选项数据
      statusOptions: [
        { label: "跟进中", value: "跟进中" },
        { label: "已落地", value: "已落地" },
        { label: "已废弃", value: "已废弃" }
      ]
    };
  },
  onLoad(options) {
    // 记录请求参数，便于调试
    console.log("拓展详情页面接收到的参数:", options);

    // 获取groupCode参数
    if (options.groupCode) {
      this.groupCode = options.groupCode;
    } else {
      uni.showToast({
        title: "缺少集团单位编码",
        icon: "none"
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    }

    // 获取expansionId参数
    if (options.expansionId) {
      this.expansionId = options.expansionId;
      // 获取拓展详情和跟进记录
      this.getExpansionDetail();
      this.getFollowList();
    } else {
      uni.showToast({
        title: "缺少拓展项ID",
        icon: "none"
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    }
  },
  methods: {
    // 页面滚动处理
    onScroll(e) {
      const currentScrollTop = e.detail.scrollTop;

      // 只有滚动距离超过一定值才触发按钮隐藏
      if (currentScrollTop > 50) {
        // 判断滚动方向
        if (currentScrollTop > this.lastScrollTop) {
          // 向下滚动，隐藏底部按钮
          this.showBottomActions = false;
        } else {
          // 向上滚动，显示底部按钮
          this.showBottomActions = true;
        }
      } else {
        // 顶部区域始终显示按钮
        this.showBottomActions = true;
      }

      // 保存当前滚动位置用于下次比较
      this.lastScrollTop = currentScrollTop;
    },

    // 下拉刷新处理
    onRefresh() {
      this.isRefreshing = true;

      // 并行请求拓展详情和跟进记录
      Promise.all([this.getExpansionDetail(), this.getFollowList()])
        .then(() => {
          // 结束刷新状态
          this.isRefreshing = false;

          // 提示刷新完成
          uni.showToast({
            title: "刷新成功",
            icon: "none"
          });
        })
        .catch(() => {
          // 结束刷新状态
          this.isRefreshing = false;
        });
    },

    // 获取拓展记录详情
    getExpansionDetail() {
      console.log("开始获取拓展详情，expansionId:", this.expansionId);

      // 显示加载提示
      uni.showLoading({
        title: "加载中..."
      });

      // 返回Promise
      return new Promise((resolve, reject) => {
        // 调用接口获取拓展详情
        this.$http
          .sendRequest("zhanke/expansion_list", "POST", {
            groupCode: this.groupCode,
            expansionId: this.expansionId
          })
          .then(res => {
            uni.hideLoading();
            console.log("拓展详情API返回:", res.data);

            if (
              res.data &&
              res.data.code === 200 &&
              res.data.data.list &&
              res.data.data.list.length > 0
            ) {
              // 获取第一条记录
              const detail = res.data.data.list[0];

              // 状态文本对应
              const statusMap = {
                跟进中: "跟进中",
                已落地: "已落地",
                已废弃: "已废弃"
              };

              // 设置拓展信息
              this.expansionInfo = {
                id: detail.id,
                groupName: detail.groupName,
                categoryName: this.getCategoryName(detail.category),
                productName: detail.productName,
                quantity: detail.quantity || 0,
                amount: detail.estimatedAmount || 0,
                expectedTime: detail.expectedLandingDate || "",
                createTime: detail.createTime || "",
                status: statusMap[detail.status] || "progress",
                isProject: detail.isProject || false,
                policy: detail.policyRate || "",
                manager: this.getManagerByCategory(detail.category)
              };

              console.log("拓展详情获取成功:", this.expansionInfo);
              resolve();
            } else {
              console.error("获取拓展详情失败:", res.data.msg);
              uni.showToast({
                title: res.data.msg || "获取拓展详情失败",
                icon: "none"
              });
              reject(new Error(res.data.msg || "获取拓展详情失败"));
            }
          })
          .catch(err => {
            uni.hideLoading();
            console.error("获取拓展详情出错:", err);
            uni.showToast({
              title: "网络请求失败",
              icon: "none"
            });
            reject(err);
          });
      });
    },

    // 获取跟进记录列表
    getFollowList() {
      console.log("开始获取跟进记录，expansionId:", this.expansionId);

      // 显示加载提示
      uni.showLoading({
        title: "加载中..."
      });

      // 返回Promise
      return new Promise((resolve, reject) => {
        // 调用接口获取跟进记录
        this.$http
          .sendRequest("zhanke/expansion_follow_list", "POST", {
            expansionId: this.expansionId,
            page: 1,
            limit: 50
          })
          .then(res => {
            uni.hideLoading();
            console.log("跟进记录API返回:", res.data);

            if (res.data && res.data.code === 200 && res.data.data.list) {
              // 转换API返回的数据为组件需要的格式
              this.followList = res.data.data.list.map(item => {
                // 处理状态
                let status = "跟进中";
                if (item.status === "已落地") {
                  status = "已落地";
                } else if (item.status === "已废弃") {
                  status = "已废弃";
                }

                return {
                  id: item.id,
                  status: status,
                  followTime: item.followDate || item.createTime,
                  follower: item.manager || "系统",
                  content: item.followContent,
                  actualAmount: item.actualAmount,
                  photos: item.photos || []
                };
              });

              console.log("跟进记录获取成功:", this.followList);
              resolve();
            } else {
              console.log("没有找到跟进记录或接口返回错误");
              this.followList = [];
              resolve([]); // 没有记录也视为成功，只是列表为空
            }
          })
          .catch(err => {
            uni.hideLoading();
            console.error("获取跟进记录出错:", err);
            uni.showToast({
              title: "获取跟进记录失败",
              icon: "none"
            });
            this.followList = [];
            reject(err);
          });
      });
    },

    // 格式化金额
    formatMoney(amount) {
      return amount.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    },

    // 获取状态文本
    getStatusText(status) {
      if (status === "跟进中") return "跟进中";
      if (status === "已落地") return "已落地";
      if (status === "已废弃") return "已废弃";
      return "未知";
    },

    // 预览图片
    previewImage(urls, current) {
      uni.previewImage({
        urls: urls,
        current: current
      });
    },

    // 显示添加跟进弹窗
    showAddFollowPopup() {
      // 设置今天的日期，格式为YYYY-MM-DD
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, "0");
      const day = String(now.getDate()).padStart(2, "0");
      const currentDate = `${year}-${month}-${day}`;

      // 重置表单
      this.form = {
        id: "", // 清空id，表示新增操作
        status: "progress",
        statusText: "跟进中",
        followTime: currentDate,
        content: "",
        actualAmount: "",
        signDate: ""
      };

      // 设置弹窗标题和编辑状态
      this.popupTitle = "新增跟进记录";
      this.isEdit = false;

      // 显示弹窗
      this.showPopup = true;
    },

    // 关闭弹窗
    closePopup() {
      this.showPopup = false;

      // 延迟清理数据，避免闪烁
      setTimeout(() => {
        this.form = {
          id: "",
          status: "",
          statusText: "",
          followTime: "",
          content: "",
          actualAmount: "",
          signDate: ""
        };
        this.isEdit = false;
      }, 300);
    },

    // 点击遮罩关闭弹窗
    onMaskClick() {
      this.closePopup();
    },

    // 选择跟进状态
    onStatusConfirm(e) {
      this.form.status = e[0].value;
      this.form.statusText = e[0].label;
    },

    // 获取当前日期
    getCurrentDate(onlyDate) {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, "0");
      const day = String(now.getDate()).padStart(2, "0");
      if (onlyDate) {
        return `${year}-${month}-${day}`;
      } else {
        const hour = String(now.getHours()).padStart(2, "0");
        const minute = String(now.getMinutes()).padStart(2, "0");
        const second = String(now.getSeconds()).padStart(2, "0");
        return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
      }
    },

    // 日期选择改变
    dateChange(e) {
      this.form.followTime = e.detail.value;
    },

    // 选择签约日期
    onSignDateConfirm(e) {
      this.form.signDate = this.formatDate(e);
      this.showSignDatePicker = false;
    },

    // 格式化日期时间
    formatDateTime(date) {
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, "0");
      const day = String(d.getDate()).padStart(2, "0");
      const hour = String(d.getHours()).padStart(2, "0");
      const minute = String(d.getMinutes()).padStart(2, "0");
      return `${year}-${month}-${day} ${hour}:${minute}`;
    },

    // 格式化日期
    formatDate(date) {
      if (!date) return "";
      // 日期已经是YYYY-MM-DD格式，直接返回
      if (
        typeof date === "string" &&
        date.length === 10 &&
        date.includes("-")
      ) {
        return date;
      }

      try {
        const d = new Date(date);
        const year = d.getFullYear();
        const month = String(d.getMonth() + 1).padStart(2, "0");
        const day = String(d.getDate()).padStart(2, "0");
        return `${year}-${month}-${day}`;
      } catch (e) {
        console.error("日期格式化错误:", e);
        return date; // 如果出错则返回原始日期
      }
    },

    // 验证表单
    validateForm() {
      if (!this.form.status) {
        uni.showToast({
          title: "请选择跟进状态",
          icon: "none"
        });
        return false;
      }
      if (!this.form.followTime) {
        uni.showToast({
          title: "请选择跟进日期",
          icon: "none"
        });
        return false;
      }
      if (!this.form.content) {
        uni.showToast({
          title: "请输入跟进情况",
          icon: "none"
        });
        return false;
      }

      if (this.form.status === "已落地") {
        if (!this.form.actualAmount) {
          uni.showToast({
            title: "请输入实际签约金额",
            icon: "none"
          });
          return false;
        }
        if (!this.form.signDate) {
          uni.showToast({
            title: "请选择签约日期",
            icon: "none"
          });
          return false;
        }
      }

      return true;
    },

    // 保存跟进记录
    saveFollow() {
      if (!this.form.followTime) {
        uni.showToast({
          title: "请选择跟进日期",
          icon: "none"
        });
        return;
      }

      if (!this.form.content) {
        uni.showToast({
          title: "请输入跟进情况",
          icon: "none"
        });
        return;
      }

      this.isSaving = true;

      // 显示加载
      uni.showLoading({
        title: this.isEdit ? "更新中..." : "保存中...",
        mask: true
      });

      // 格式化日期为中文显示，如：8月7日
      const dateParts = this.form.followTime.split("-");
      const month = parseInt(dateParts[1]);
      const day = parseInt(dateParts[2]);
      const chineseDate = `${month}月${day}日`;

      // 组合内容，自动添加日期前缀
      const fullContent = `${chineseDate}，${this.form.content}`;

      // 准备请求参数
      const params = {
        expansionId: this.expansionId,
        followDate: this.form.followTime,
        followContent: fullContent,
        status: this.form.status,
        actualAmount: this.form.actualAmount
      };

      // 编辑模式需要添加记录ID
      if (this.isEdit && this.form.id) {
        params.id = this.form.id;
      }

      // 调用不同的接口
      const apiUrl = this.isEdit
        ? "zhanke/expansion_follow_update"
        : "zhanke/expansion_follow_add";

      // 调用接口保存跟进记录
      this.$http
        .sendRequest(apiUrl, "POST", params)
        .then(res => {
          uni.hideLoading();
          this.isSaving = false;

          if (res.data && res.data.code === 200) {
            // 获取新记录ID或使用现有ID
            const recordId = this.isEdit
              ? this.form.id
              : res.data.data.id || `follow_${Date.now()}`;

            // 获取当前用户信息
            const userInfo = uni.getStorageSync("userInfo") || {};
            const follower = userInfo.name || "当前用户";

            // 创建记录对象
            const followRecord = {
              id: recordId,
              status: this.form.status,
              followTime: this.form.followTime,
              follower: follower,
              content: fullContent,
              actualAmount: this.form.actualAmount,
              photos: []
            };

            if (this.isEdit) {
              // 更新现有记录
              const index = this.followList.findIndex(
                item => item.id === recordId
              );
              if (index !== -1) {
                this.followList.splice(index, 1, followRecord);
              }
            } else {
              // 添加到列表开头
              this.followList.unshift(followRecord);
            }

            // 如果是标记为签约或失败，更新拓展项状态
            if (
              this.form.status === "已落地" ||
              this.form.status === "已废弃"
            ) {
              this.expansionInfo.status = this.form.status;
            }

            this.closePopup();

            // 显示提示
            uni.showToast({
              title: this.isEdit ? "更新成功" : "添加成功",
              icon: "success"
            });
          } else {
            uni.showToast({
              title: res.data.msg || (this.isEdit ? "更新失败" : "保存失败"),
              icon: "none"
            });
          }
        })
        .catch(err => {
          uni.hideLoading();
          this.isSaving = false;
          console.error("保存跟进记录出错:", err);
          uni.showToast({
            title: "网络请求失败，请重试",
            icon: "none"
          });
        });
    },

    // 标记为失败
    markAsFailed() {
      uni.showModal({
        title: "提示",
        content: '确定要将此拓展记录标记为"已废弃"吗？',
        success: res => {
          if (res.confirm) {
            // 设置当前日期时间
            const now = new Date();
            const year = now.getFullYear();
            const month = String(now.getMonth() + 1).padStart(2, "0");
            const day = String(now.getDate()).padStart(2, "0");
            const currentDate = `${year}-${month}-${day}`;

            // 显示弹窗并预设状态为废弃
            this.form = {
              status: "已废弃",
              statusText: "已废弃",
              followTime: currentDate,
              content: "该项目经过多次沟通，客户表示暂时没有需求，暂不跟进",
              actualAmount: "",
              signDate: ""
            };
            this.showPopup = true;
          }
        }
      });
    },

    // 标记为签约
    markAsCompleted() {
      uni.showModal({
        title: "提示",
        content: '确定要将此拓展记录标记为"已签约"吗？',
        success: res => {
          if (res.confirm) {
            // 设置当前日期时间
            const now = new Date();
            const year = now.getFullYear();
            const month = String(now.getMonth() + 1).padStart(2, "0");
            const day = String(now.getDate()).padStart(2, "0");
            const currentDate = `${year}-${month}-${day}`;

            // 显示弹窗并预设状态为签约
            this.form = {
              status: "已落地",
              statusText: "已落地", // 使用后端需要的"已落地"状态文本
              followTime: currentDate,
              content:
                "该项目经过多次沟通跟进，目前已于我公司达成共识，已经签约",
              actualAmount: this.expansionInfo.amount,
              signDate: currentDate
            };
            this.showPopup = true;
          }
        }
      });
    },

    // 获取时间部分
    getTimeOnly(timeString) {
      // 由于跟进时间只使用日期部分，不再需要显示时间
      return "";
    },

    // 跳转到编辑页面
    goToEditPage() {
      uni.navigateTo({
        url: `/pages/business/expansion/edit?groupCode=${this.groupCode}&expansionId=${this.expansionId}`
      });
    },

    // 根据类别代码获取类别名称
    getCategoryName(category) {
      // 直接返回类别名称，不再进行映射转换
      return category || "其他";
    },

    // 根据类别获取对应的产品主管
    getManagerByCategory(category) {
      const managerMap = {
        专线: "李晶晶",
        移动云: "乔花",
        物联网: "石慧贤",
        短彩信: "乔花",
        其他: "暂无"
      };
      return managerMap[category] || "暂无";
    },

    // 编辑跟进记录
    editFollow(item) {
      console.log("编辑跟进记录:", item);

      // 解析内容，去除日期前缀
      let content = item.content;
      const datePattern = /^\d+月\d+日，/;
      if (datePattern.test(content)) {
        content = content.replace(datePattern, "");
      }

      // 设置表单数据
      this.form = {
        id: item.id, // 添加id字段，标识是编辑操作
        status: item.status,
        statusText: this.getStatusTextByValue(item.status),
        followTime: this.extractDate(item.followTime),
        content: content,
        actualAmount: item.actualAmount || "",
        signDate: item.signDate || ""
      };

      // 显示弹窗
      this.showPopup = true;

      // 修改弹窗标题为"编辑跟进记录"
      this.popupTitle = "编辑跟进记录";
      this.isEdit = true;
    },

    // 根据状态值获取状态文本
    getStatusTextByValue(status) {
      switch (status) {
        case "跟进中":
          return "跟进中";
        case "已落地":
          return "已落地";
        case "已废弃":
          return "已废弃";
        default:
          return "跟进中";
      }
    },

    // 从日期时间字符串中提取日期部分
    extractDate(dateTimeStr) {
      if (!dateTimeStr) return "";
      return dateTimeStr.split(" ")[0];
    },

    // 删除跟进记录
    deleteFollow(id) {
      console.log("删除跟进记录:", id);

      // 确认删除
      uni.showModal({
        title: "确认删除",
        content: "确定要删除这条跟进记录吗？删除后不可恢复。",
        confirmColor: "#fa3534",
        success: res => {
          if (res.confirm) {
            // 用户点击确定，执行删除操作
            this.executeDeleteFollow(id);
          }
        }
      });
    },

    // 执行删除跟进记录的操作
    executeDeleteFollow(id) {
      // 显示加载
      uni.showLoading({
        title: "删除中...",
        mask: true
      });

      // 调用接口删除跟进记录
      this.$http
        .sendRequest("zhanke/expansion_follow_delete", "POST", {
          id: id
        })
        .then(res => {
          uni.hideLoading();

          if (res.data && res.data.code === 200) {
            // 从列表中移除该记录
            const index = this.followList.findIndex(item => item.id === id);
            if (index !== -1) {
              this.followList.splice(index, 1);
            }

            // 显示提示
            uni.showToast({
              title: "删除成功",
              icon: "success"
            });
          } else {
            uni.showToast({
              title: res.data.msg || "删除失败，请重试",
              icon: "none"
            });
          }
        })
        .catch(err => {
          uni.hideLoading();
          console.error("删除跟进记录出错:", err);
          uni.showToast({
            title: "网络请求失败，请重试",
            icon: "none"
          });
        });
    }
  }
};
</script>

<style lang="scss">
.expansion-detail-container {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-bottom: 120rpx;
  background-image: linear-gradient(
    to bottom,
    rgba(230, 240, 255, 0.5),
    rgba(245, 250, 255, 0.8)
  );
  position: relative;

  .detail-scroll-view {
    height: calc(100vh - var(--status-bar-height) - 88rpx);
  }

  /* 导航栏占位，防止内容被固定导航栏遮挡 */
  .navbar-placeholder {
    height: 88rpx;
    /* 如果有状态栏，可能需要增加高度 */
    padding-top: var(--status-bar-height);
  }

  .content {
    padding: 20rpx;
  }

  .header-card {
    position: relative;
    background: linear-gradient(135deg, #ffffff, #f5faff);
    border-radius: 20rpx;
    padding: 40rpx 30rpx;
    margin-bottom: 24rpx;
    box-shadow: 0 8rpx 30rpx rgba(43, 133, 228, 0.08);
    border: 1rpx solid rgba(230, 240, 255, 0.6);
    transform: translateZ(0);
    overflow: hidden;
    transition: all 0.3s ease;

    &:active {
      transform: translateY(2rpx);
      box-shadow: 0 4rpx 15rpx rgba(43, 133, 228, 0.05);
    }

    &::before {
      content: "";
      position: absolute;
      top: 0;
      left: 0;
      width: 6rpx;
      height: 100%;
    }

    .status-badge {
      position: absolute;
      top: 0;
      right: 0;
      padding: 10rpx 30rpx;
      font-size: 24rpx;
      color: #ffffff;
      font-weight: 500;
      border-radius: 0 20rpx 0 20rpx;
      box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.15);
      z-index: 2;

      &.status-progress {
        background: linear-gradient(90deg, #2b85e4, #36a3f7);
      }

      &.status-completed {
        background: linear-gradient(90deg, #19be6b, #1fd078);
      }

      &.status-failed {
        background: linear-gradient(90deg, #fa3534, #ff6b6b);
      }
    }

    .group-info {
      margin-bottom: 30rpx;

      .group-name {
        font-size: 40rpx;
        font-weight: 600;
        color: #2c3e50;
        margin-bottom: 14rpx;
        letter-spacing: 1rpx;
      }

      .info-meta {
        font-size: 28rpx;
        color: #7f8c8d;
        opacity: 0.9;
      }
    }

    .amount-info {
      padding-top: 24rpx;
      border-top: 1px dashed rgba(230, 240, 255, 0.8);
      display: flex;
      align-items: baseline;

      .amount-label {
        font-size: 26rpx;
        color: #95a5a6;
        margin-right: 14rpx;
      }

      .amount-value {
        font-size: 44rpx;
        font-weight: bold;
        color: #e74c3c;
        letter-spacing: 1rpx;
      }

      .amount-unit {
        font-size: 26rpx;
        color: #95a5a6;
        margin-left: 10rpx;
      }
    }
  }

  .info-section {
    margin-bottom: 40rpx;

    .section-title {
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;
      padding: 0 20rpx;

      text {
        font-size: 34rpx;
        font-weight: bold;
        margin-left: 10rpx;
        color: #333;
      }

      .edit-expansion {
        margin-left: auto;
        display: flex;
        align-items: center;
        padding: 8rpx 16rpx;
        font-size: 26rpx;
        color: #2b85e4;
        background-color: rgba(43, 133, 228, 0.1);
        border-radius: 30rpx;
        transition: all 0.3s;

        text {
          font-size: 26rpx;
          font-weight: normal;
          margin-left: 6rpx;
          color: #2b85e4;
        }

        &:active {
          transform: scale(0.95);
          background-color: rgba(43, 133, 228, 0.2);
        }
      }
    }

    .info-items {
      padding: 0 10rpx;
    }

    .info-card {
      background-color: #fff;
      border-radius: 16rpx;
      margin-bottom: 20rpx;
      padding: 24rpx;
      box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
      transition: all 0.3s;

      &:hover {
        transform: translateY(-4rpx);
        box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.08);
      }
    }

    .info-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20rpx;
      padding-bottom: 16rpx;
      border-bottom: 1px solid rgba(230, 230, 230, 0.6);

      &:last-child {
        margin-bottom: 0;
        padding-bottom: 0;
        border-bottom: none;
      }
    }

    .item-label {
      font-size: 28rpx;
      color: #666;
      flex: 0 0 auto;
      width: 40%;
    }

    .item-value {
      font-size: 28rpx;
      color: #333;
      text-align: right;
      font-weight: 500;
      max-width: 60%;
      word-break: break-all;

      &.highlight {
        color: #2b85e4;
        font-weight: bold;
      }

      &.price {
        color: #f56c6c;
        font-weight: bold;
      }
    }

    .policy-card {
      display: flex;
      flex-direction: column;
    }

    .card-subtitle {
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;

      text {
        margin-left: 10rpx;
        font-size: 30rpx;
        font-weight: bold;
        color: #333;
      }
    }

    .policy-text {
      font-size: 28rpx;
      color: #333;
      line-height: 1.6;
      padding: 16rpx;
      background-color: #f8f9fa;
      border-radius: 12rpx;
      min-height: 120rpx;
    }
  }

  .follow-section {
    background-color: #ffffff;
    border-radius: 20rpx;
    padding: 30rpx 24rpx;
    margin-bottom: 24rpx;
    box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.05);
    border: 1rpx solid rgba(230, 240, 255, 0.6);
    transition: all 0.3s ease;

    &:hover {
      box-shadow: 0 10rpx 40rpx rgba(0, 0, 0, 0.08);
    }
  }

  .section-title {
    display: flex;
    align-items: center;
    margin-bottom: 30rpx;
    font-size: 32rpx;
    font-weight: 600;
    color: #2c3e50;
    position: relative;
    padding-bottom: 16rpx;
    border-bottom: 1px solid rgba(230, 240, 255, 0.8);

    text {
      margin-left: 14rpx;
    }

    &::after {
      content: "";
      position: absolute;
      bottom: -1px;
      left: 0;
      width: 80rpx;
      height: 4rpx;
      background: linear-gradient(to right, #2b85e4, #36a3f7);
      border-radius: 4rpx;
    }

    .add-follow {
      display: flex;
      align-items: center;
      margin-left: auto;
      font-size: 28rpx;
      color: #2b85e4;
      font-weight: normal;
      background: rgba(43, 133, 228, 0.08);
      padding: 8rpx 16rpx;
      border-radius: 30rpx;
      transition: all 0.3s ease;

      &:active {
        background: rgba(43, 133, 228, 0.15);
        transform: scale(0.96);
      }

      text {
        margin-left: 8rpx;
      }
    }

    .edit-expansion {
      display: flex;
      align-items: center;
      margin-left: auto;
      font-size: 28rpx;
      color: #2b85e4;
      font-weight: normal;
      background: rgba(43, 133, 228, 0.08);
      padding: 8rpx 16rpx;
      border-radius: 30rpx;
      transition: all 0.3s ease;

      &:active {
        background: rgba(43, 133, 228, 0.15);
        transform: scale(0.96);
      }

      text {
        margin-left: 8rpx;
      }
    }
  }

  .follow-timeline {
    margin-top: 30rpx;
  }

  .progress-timeline {
    margin-top: 20rpx;
    border-radius: 16rpx;
    padding: 10rpx 0 10rpx 10rpx;
    border-left: none;
  }

  .timeline-item {
    display: flex;
    position: relative;
    padding: 24rpx 0;
    border-bottom: 1px dashed rgba(230, 240, 255, 0.8);
    transition: all 0.3s ease;
    animation: fadeIn 0.6s ease;

    @keyframes fadeIn {
      from {
        opacity: 0;
        transform: translateY(10rpx);
      }
      to {
        opacity: 1;
        transform: translateY(0);
      }
    }

    &:hover {
      background-color: rgba(245, 250, 255, 0.6);
    }
  }

  .timeline-item:last-child {
    border-bottom: none;
    padding-bottom: 10rpx;
  }

  .timeline-left {
    position: relative;
    width: 24rpx;
    height: 100%;
    flex-shrink: 0;
  }

  .timeline-dot {
    width: 16rpx;
    height: 16rpx;
    border-radius: 50%;
    background: linear-gradient(135deg, #2b85e4, #36a3f7);
    position: absolute;
    top: 8rpx;
    left: 4rpx;
    box-shadow: 0 0 0 4rpx rgba(43, 133, 228, 0.1),
      0 0 10rpx rgba(43, 133, 228, 0.3);
    animation: pulse 3s infinite;

    @keyframes pulse {
      0% {
        box-shadow: 0 0 0 0 rgba(43, 133, 228, 0.4);
      }
      70% {
        box-shadow: 0 0 0 8rpx rgba(43, 133, 228, 0);
      }
      100% {
        box-shadow: 0 0 0 0 rgba(43, 133, 228, 0);
      }
    }

    &.status-completed {
      background: linear-gradient(135deg, #19be6b, #1fd078);
      box-shadow: 0 0 0 4rpx rgba(25, 190, 107, 0.1);
    }

    &.status-failed {
      background: linear-gradient(135deg, #fa3534, #ff6b6b);
      box-shadow: 0 0 0 4rpx rgba(250, 53, 52, 0.1);
    }
  }

  .timeline-line {
    width: 2rpx;
    position: absolute;
    top: 24rpx;
    bottom: -12rpx;
    left: 10rpx;
    background: linear-gradient(
      to bottom,
      rgba(43, 133, 228, 0.5),
      rgba(43, 133, 228, 0.1)
    );
  }

  .timeline-right {
    flex: 1;
    padding-left: 20rpx;
  }

  .timeline-header {
    display: flex;
    align-items: center;
    margin-bottom: 12rpx;
    justify-content: space-between;
    position: relative;
    height: 48rpx;
  }

  .timeline-date {
    font-size: 15px;
    color: #2b85e4;
    font-weight: 600;
    padding: 4rpx 0;
    max-width: 60%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .timeline-actions {
    display: flex;
    align-items: center;
    height: 100%;
  }

  .timeline-user {
    font-size: 13px;
    color: #7f8c8d;
    font-weight: 500;
    padding: 4rpx 8rpx;
    background-color: rgba(230, 240, 255, 0.5);
    border-radius: 4rpx;
    display: flex;
    align-items: center;
    max-width: 160rpx;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .timeline-content {
    font-size: 14px;
    color: #34495e;
    line-height: 1.6;
    background-color: #f8f9fa;
    padding: 20rpx;
    border-radius: 12rpx;
    position: relative;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.03);
    border: 1px solid rgba(230, 240, 250, 0.7);
    transition: all 0.3s ease;
    transform-origin: left center;
    animation: contentScale 0.3s ease;

    @keyframes contentScale {
      from {
        opacity: 0.7;
        transform: scaleX(0.95);
      }
      to {
        opacity: 1;
        transform: scaleX(1);
      }
    }

    &:hover {
      box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.05);
      transform: translateY(-2rpx);
    }
  }

  .content-header {
    margin-bottom: 12rpx;
    display: flex;
    align-items: center;
    min-height: 36rpx;
  }

  .content-text {
    margin-bottom: 10px;
  }

  .content-details {
    margin-top: 10px;
    border-top: 1px dashed rgba(230, 230, 230, 0.8);
    padding-top: 10px;
  }

  .detail-item {
    display: flex;
    margin-bottom: 5px;
  }

  .detail-label {
    width: 80px;
    color: #7f8c8d;
    font-size: 12px;
  }

  .detail-value {
    flex: 1;
    color: #34495e;
    font-size: 12px;
    font-weight: 500;
  }

  .timeline-images {
    display: flex;
    flex-wrap: wrap;
    margin-top: 10px;
    border-top: 1px dashed rgba(230, 230, 230, 0.8);
    padding-top: 10px;
  }

  .timeline-image {
    width: 70px;
    height: 70px;
    margin-right: 8px;
    margin-bottom: 8px;
    border-radius: 8px;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;

    &:hover {
      transform: scale(1.05);
      box-shadow: 0 4px 10px rgba(0, 0, 0, 0.15);
    }
  }

  .bottom-actions {
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
    display: flex;
    padding: 20rpx;
    background-color: rgba(255, 255, 255, 0.98);
    box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.08);
    z-index: 100;
    animation: slideUp 0.5s ease;
    transition: transform 0.3s ease;

    @keyframes slideUp {
      from {
        transform: translateY(100%);
      }
      to {
        transform: translateY(0);
      }
    }

    .u-button {
      flex: 1;
      margin: 0 10rpx;
      border-radius: 10rpx !important;
      box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1) !important;
      transition: all 0.3s ease !important;

      &:active {
        transform: scale(0.98) !important;
        box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.1) !important;
      }
    }
  }
}

.custom-popup-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 900;
  animation: fadeIn 0.3s ease;

  @keyframes fadeIn {
    from {
      opacity: 0;
    }
    to {
      opacity: 1;
    }
  }
}

.custom-popup-content {
  background-color: #ffffff;
  padding: 30rpx;
  border-radius: 24rpx;
  width: 90%;
  max-width: 800rpx;
  position: relative;
  z-index: 901;
  box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.15);
  transform: translateY(0);
  animation: popup-in 0.3s ease-out;

  @keyframes popup-in {
    0% {
      opacity: 0;
      transform: translateY(20rpx);
    }
    100% {
      opacity: 1;
      transform: translateY(0);
    }
  }
}

.custom-popup-close {
  position: absolute;
  top: 16rpx;
  right: 16rpx;
  font-size: 40rpx;
  color: #909399;
  cursor: pointer;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.3s ease;

  &:hover {
    background-color: rgba(0, 0, 0, 0.05);
    color: #606266;
  }
}

.popup-content {
  padding: 10rpx;
}

.popup-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 40rpx;
  text-align: center;
  position: relative;

  &::after {
    content: "";
    position: absolute;
    bottom: -10rpx;
    left: 50%;
    transform: translateX(-50%);
    width: 60rpx;
    height: 4rpx;
    background: linear-gradient(to right, #2b85e4, #36a3f7);
    border-radius: 2rpx;
  }
}

.form-content {
  margin-bottom: 40rpx;
}

.form-group {
  margin-bottom: 30rpx;
}

.form-label {
  font-size: 28rpx;
  color: #606266;
  margin-bottom: 12rpx;
  display: block;
  font-weight: 500;

  &.required:before {
    content: "*";
    color: #ff4d4f;
    margin-right: 8rpx;
  }
}

.form-control {
  position: relative;
}

.date-picker,
.status-select {
  padding: 16rpx 0;
  border-bottom: 1px solid #e4e7ed;
  transition: all 0.3s ease;

  &:focus-within {
    border-color: #2b85e4;
  }
}

.picker-value,
.input-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 28rpx;
  color: #333;
  height: 48rpx;
}

.popup-footer {
  display: flex;
  justify-content: space-between;
  gap: 30rpx;
}

.popup-footer u-button {
  flex: 1;
  height: 80rpx !important;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;

  &:active {
    transform: scale(0.96);
  }

  &::after {
    border-radius: 40rpx !important;
  }
}

/* 产品信息样式 */
.popup-product-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
  padding-bottom: 20rpx;
  border-bottom: 1px dashed rgba(230, 230, 230, 0.8);
}

.popup-product-name {
  font-size: 32rpx;
  font-weight: 600;
  color: #2c3e50;
}

.popup-product-status {
  font-size: 24rpx;
  padding: 6rpx 20rpx;
  border-radius: 30rpx;
  color: #fff;
  font-weight: 500;
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);

  &.status-progress {
    background: linear-gradient(90deg, #2b85e4, #36a3f7);
  }

  &.status-completed {
    background: linear-gradient(90deg, #19be6b, #1fd078);
  }

  &.status-failed {
    background: linear-gradient(90deg, #fa3534, #ff6b6b);
  }
}

.action-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 48rpx;
  height: 48rpx;
  margin-left: 12rpx;
  border-radius: 50%;
  cursor: pointer;
  transition: all 0.2s ease;
}

.edit-btn {
  background-color: rgba(43, 133, 228, 0.1);
}

.edit-btn:active {
  background-color: rgba(43, 133, 228, 0.2);
  transform: scale(0.92);
}

.delete-btn {
  background-color: rgba(250, 53, 52, 0.1);
}

.delete-btn:active {
  background-color: rgba(250, 53, 52, 0.2);
  transform: scale(0.92);
}

/* 删除不再需要的样式 */
.record-actions {
  display: none;
}

.timeline-content::before {
  content: "";
  position: absolute;
  left: -8px;
  top: 12px;
  width: 0;
  height: 0;
  border-top: 8px solid transparent;
  border-bottom: 8px solid transparent;
  border-right: 8px solid #f8f9fa;
}
</style> 